package com.yami.trading.api.controller;

import cn.hutool.core.util.StrUtil;
import com.qiniu.util.StringUtils;
import com.yami.trading.api.model.AddPaymentMethodModel;
import com.yami.trading.api.model.IdModel;
import com.yami.trading.api.model.PaymentMethodModel;
import com.yami.trading.api.service.UserCacheService;
import com.yami.trading.api.util.ServletUtil;
import com.yami.trading.bean.constans.UserConstants;
import com.yami.trading.bean.model.C2cPaymentMethod;
import com.yami.trading.bean.model.C2cPaymentMethodConfig;
import com.yami.trading.bean.model.C2cTranslate;
import com.yami.trading.bean.model.User;
import com.yami.trading.common.constants.Constants;
import com.yami.trading.common.constants.RedisKeys;
import com.yami.trading.common.domain.Result;
import com.yami.trading.common.exception.YamiShopBindException;
import com.yami.trading.common.util.IPHelper;
import com.yami.trading.security.common.util.SecurityUtils;
import com.yami.trading.service.c2c.C2cAdvertService;
import com.yami.trading.service.c2c.C2cPaymentMethodConfigService;
import com.yami.trading.service.c2c.C2cPaymentMethodService;
import com.yami.trading.service.c2c.C2cTranslateService;
import com.yami.trading.service.syspara.SysparaService;
import com.yami.trading.service.system.LogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("api/paymentMethod")
@Api(tags = "收款方式")
public class ApiPaymentMethodController {
    @Autowired
    C2cPaymentMethodConfigService c2cPaymentMethodConfigService;
    @Autowired
    C2cPaymentMethodService c2cPaymentMethodService;
    @Autowired
    UserCacheService userCacheService;
    @Autowired
    LogService logService;
    @Autowired
    SysparaService sysparaService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    C2cTranslateService c2cTranslateService;
    @Autowired
    C2cAdvertService c2cAdvertService;

    @ApiOperation(value = "获取收款方式列表")
    @RequestMapping("list")
    public Result<Map<String, String>> getPaymentMethod(@Valid PaymentMethodModel paymentMethodModel) {
        String language = paymentMethodModel.getLanguage();
        Map<String, String> methodConfigMap = this.c2cPaymentMethodConfigService.getMethodConfigMap();
        // 多语言
        for (String id : methodConfigMap.keySet()) {
            String name = methodConfigMap.get(id);
            if (null != name) {
                C2cTranslate trans = c2cTranslateService.get(name, language);
                if (null != trans) {
                    methodConfigMap.put(id, trans.getTranslate());
                }
            }
        }
        return Result.succeed(methodConfigMap);
    }

    @ApiOperation(value = "新增收款方式")
    @RequestMapping("add")
    public Result<?> add(@Valid AddPaymentMethodModel model) {
        String language = ServletUtil.getRequest().getParameter("language");
        if (StringUtils.isNullOrEmpty(model.getMethod_config_id())) {
            throw new YamiShopBindException("支付方式模板不正确");
        }
        if (StringUtils.isNullOrEmpty(model.getReal_name())) {
            throw new YamiShopBindException("真实姓名必填");
        }
        if (StringUtils.isNullOrEmpty(model.getParam_value1())) {
            throw new YamiShopBindException("参数值1必填");
        }
        if (model.getReal_name().length() > 20) {
            if (language.equals("zh-CN")) {
                throw new YamiShopBindException("真实姓名长度大于20");
            } else {
                throw new YamiShopBindException("Real name length greater than 20");
            }
        }
        if (model.getRemark().length() > 100) {
            if (language.equals("zh-CN")) {
                throw new YamiShopBindException("备注长度大于100");
            } else {
                throw new YamiShopBindException("Note length greater than 100");
            }
        }
        C2cPaymentMethodConfig methodConfig = c2cPaymentMethodConfigService.getById(model.getMethod_config_id());
        if (null == methodConfig) {
            throw new YamiShopBindException("支付方式模板不存在");
        }
        if (!StrUtil.isEmpty(model.getParam_value1())) {
            if (model.getParam_value1().length() > 25) {
                throw new YamiShopBindException(methodConfig.getParamName1() + "长度大于25");
            }
        }
        if (!StrUtil.isEmpty(model.getParam_value2())) {
            if (model.getParam_value2().length() > 25) {
                throw new YamiShopBindException(methodConfig.getParamName2() + "长度大于25");
            }
        }
        String partyId = SecurityUtils.getUser().getUserId();
        if (null == partyId) {
            throw new YamiShopBindException("请重新登录");
        }
        // C2C用户和承兑商添加支付方式最大数量
        Map<String, C2cPaymentMethod> methodMap = c2cPaymentMethodService.getByPartyId(partyId);
        Object obj = this.sysparaService.find("c2c_payment_method_count_max");
        if (null != obj) {
            if (methodMap.size() >= Integer.valueOf(this.sysparaService.find("c2c_payment_method_count_max").getSvalue()).intValue()) {
                throw new YamiShopBindException("支付方式数量已达上限");
            }
        }
        C2cPaymentMethod method = new C2cPaymentMethod();
        method.setPartyId(partyId);
        method.setMethodConfigId(model.getMethod_config_id());
        method.setMethodType(methodConfig.getMethodType());
        method.setMethodName(methodConfig.getMethodName());
        method.setMethodImg(methodConfig.getMethodImg());
        method.setRealName(model.getReal_name());
        method.setParamName1(methodConfig.getParamName1());
        method.setParamValue1(model.getParam_value1());
        method.setParamName2(methodConfig.getParamName2());
        method.setParamValue2(model.getParam_value2());
        method.setParamName3(methodConfig.getParamName3());
        method.setParamValue3(model.getParam_value3());
        method.setParamName4(methodConfig.getParamName4());
        method.setParamValue4(model.getParam_value4());
        method.setParamName5(methodConfig.getParamName5());
        method.setParamValue5(model.getParam_value5());
        method.setParamName6(methodConfig.getParamName6());
        method.setParamValue6(model.getParam_value6());
        method.setParamName7(methodConfig.getParamName7());
        method.setParamValue7(model.getParam_value7());
        method.setParamName8(methodConfig.getParamName8());
        method.setParamValue8(model.getParam_value8());
        method.setParamName9(methodConfig.getParamName9());
        method.setParamValue9(model.getParam_value9());
        method.setParamName10(methodConfig.getParamName10());
        method.setParamValue10(model.getParam_value10());
        method.setParamName11(methodConfig.getParamName11());
        method.setParamValue11(model.getParam_value11());
        method.setParamName12(methodConfig.getParamName12());
        method.setParamValue12(model.getParam_value12());
        method.setParamName13(methodConfig.getParamName13());
        method.setParamValue13(model.getParam_value13());
        method.setParamName14(methodConfig.getParamName14());
        method.setParamValue14(model.getParam_value14());
        method.setParamName15(methodConfig.getParamName15());
        method.setParamValue15(model.getParam_value15());
        method.setQrcode(model.getQrcode());
        method.setRemark(model.getRemark());
        method.setCreateTime(new Date());
        method.setUpdateTime(new Date());
        String id = c2cPaymentMethodService.saveData(method);
        C2cPaymentMethod methodSaved = c2cPaymentMethodService.getC2cPaymentMethod(id);
        if (null != methodSaved) {
            redisTemplate.opsForValue().set(RedisKeys.C2C_PAYMENT_METHOD_ID + methodSaved.getUuid(), methodSaved);
            Map<String, C2cPaymentMethod> map = (Map<String, C2cPaymentMethod>) redisTemplate.opsForValue().get(RedisKeys.C2C_PAYMENT_METHOD_PARTY_ID + methodSaved.getPartyId());
            if (null == map) {
                map = new HashMap<>();
            }
            map.put(methodSaved.getUuid(), methodSaved);
            redisTemplate.opsForValue().set(RedisKeys.C2C_PAYMENT_METHOD_PARTY_ID + methodSaved.getPartyId(), map);
            Map<String, String> map1 = (Map<String, String>) redisTemplate.opsForValue().get(RedisKeys.C2C_PAYMENT_METHOD_ID_TYPE);
            if (null == map1) {
                map1 = new ConcurrentHashMap<String, String>();
            }
            map1.put(methodSaved.getUuid(), String.valueOf(methodSaved.getMethodType()));
            redisTemplate.opsForValue().set(RedisKeys.C2C_PAYMENT_METHOD_ID_TYPE + methodSaved.getUuid(), map1);
        }
        String log = MessageFormat.format("ip:" + IPHelper.getIpAddr()
                        + ",用户新增支付方式,id:{0},用户PARTY_ID:{1},支付方式模板id:{2},支付方式类型:{3},支付方式名称:{4},支付方式图片:{5},真实姓名:{6},"
                        + "参数名1:{7},参数值1:{8},参数名2:{9},参数值2:{10},参数名3:{11},参数值3:{12},参数名4:{13},参数值4:{14},参数名5:{15},参数值5:{16},"
                        + "参数名6:{17},参数值6:{18},参数名7:{19},参数值7:{20},参数名8:{21},参数值8:{22},参数名9:{23},参数值9:{24},参数名10:{25},参数值10:{26},"
                        + "参数名11:{27},参数值11:{28},参数名12:{29},参数值12:{30},参数名13:{31},参数值13:{32},参数名14:{33},参数值14:{34},参数名15:{35},参数值15:{36},"
                        + "支付二维码:{37},备注:{38},创建时间:{39},更新时间:{40}",
                method.getUuid(), method.getPartyId(), method.getMethodConfigId(), method.getMethodType(), method.getMethodName(), method.getMethodImg(), method.getRealName(),
                method.getParamName1(), method.getParamValue1(), method.getParamName2(), method.getParamValue2(), method.getParamName3(), method.getParamValue3(), method.getParamName4(), method.getParamValue4(), method.getParamName5(), method.getParamValue5(),
                method.getParamName6(), method.getParamValue6(), method.getParamName7(), method.getParamValue7(), method.getParamName8(), method.getParamValue8(), method.getParamName9(), method.getParamValue9(), method.getParamName10(), method.getParamValue10(),
                method.getParamName11(), method.getParamValue11(), method.getParamName12(), method.getParamValue12(), method.getParamName13(), method.getParamValue13(), method.getParamName14(), method.getParamValue14(), method.getParamName15(), method.getParamValue15(),
                method.getQrcode(), method.getRemark(), method.getCreateTime(), method.getUpdateTime());
        User user = userCacheService.currentUser();
        logService.saveLog(user, log, UserConstants.LOG_CATEGORY_C2C);
        return Result.succeed(null);
    }

    @ApiOperation(value = "更新收款方式")
    @RequestMapping("update")
    public Result<?> update(@Valid AddPaymentMethodModel model) {
        String language = ServletUtil.getRequest().getParameter("language");
        if (StringUtils.isNullOrEmpty(model.getReal_name())) {
            throw new YamiShopBindException("真实姓名必填");
        }
        if (StringUtils.isNullOrEmpty(model.getParam_value1())) {
            throw new YamiShopBindException("参数值1必填");
        }
        if (model.getReal_name().length() > 20) {
            if (language.equals("zh-CN")) {
                throw new YamiShopBindException("真实姓名长度大于20");
            } else {
                throw new YamiShopBindException("Real name length greater than 20");
            }
        }
        if (model.getRemark().length() > 100) {
            if (language.equals("zh-CN")) {
                throw new YamiShopBindException("备注长度大于100");
            } else {
                throw new YamiShopBindException("Note length greater than 100");
            }
        }
        C2cPaymentMethod method = this.c2cPaymentMethodService.getById(model.getId());
        if (null == method) {
            throw new YamiShopBindException("支付方式不存在");
        }
        String partyId = SecurityUtils.getUser().getUserId();
        if (!method.getPartyId().equals(partyId)) {
            throw new YamiShopBindException("支付方式不匹配该用户");
        }
        String log = MessageFormat.format("ip:" + IPHelper.getIpAddr()
                        + ",用户修改支付方式,id:{0},原用户PARTY_ID:{1},原支付方式模板:{2},原支付方式类型:{3},原支付方式名称:{4},原支付方式图片:{5},原真实姓名:{6},"
                        + "原参数名1:{7},原参数值1:{8},原参数名2:{9},原参数值2:{10},原参数名3:{11},原参数值3:{12},原参数名4:{13},原参数值4:{14},原参数名5:{15},原参数值5:{16},"
                        + "原参数名6:{17},原参数值6:{18},原参数名7:{19},原参数值7:{20},原参数名8:{21},原参数值8:{22},原参数名9:{23},原参数值9:{24},原参数名10:{25},原参数值10:{26},"
                        + "原参数名11:{27},原参数值11:{28},原参数名12:{29},原参数值12:{30},原参数名13:{31},原参数值13:{32},原参数名14:{33},原参数值14:{34},原参数名15:{35},原参数值15:{36},"
                        + "原支付二维码:{37},原备注:{38},原创建时间:{39},原更新时间:{40}",
                method.getUuid(), method.getPartyId(), method.getMethodConfigId(), method.getMethodType(), method.getMethodName(), method.getMethodImg(), method.getRealName(),
                method.getParamName1(), method.getParamValue1(), method.getParamName2(), method.getParamValue2(), method.getParamName3(), method.getParamValue3(), method.getParamName4(), method.getParamValue4(), method.getParamName5(), method.getParamValue5(),
                method.getParamName6(), method.getParamValue6(), method.getParamName7(), method.getParamValue7(), method.getParamName8(), method.getParamValue8(), method.getParamName9(), method.getParamValue9(), method.getParamName10(), method.getParamValue10(),
                method.getParamName11(), method.getParamValue11(), method.getParamName12(), method.getParamValue12(), method.getParamName13(), method.getParamValue13(), method.getParamName14(), method.getParamValue14(), method.getParamName15(), method.getParamValue15(),
                method.getQrcode(), method.getRemark(), method.getCreateTime(), method.getUpdateTime());
        method.setRealName(model.getReal_name());
        method.setParamValue1(model.getParam_value1());
        method.setParamValue2(model.getParam_value2());
        method.setParamValue3(model.getParam_value3());
        method.setParamValue4(model.getParam_value4());
        method.setParamValue5(model.getParam_value5());
        method.setParamValue6(model.getParam_value6());
        method.setParamValue7(model.getParam_value7());
        method.setParamValue8(model.getParam_value8());
        method.setParamValue9(model.getParam_value9());
        method.setParamValue10(model.getParam_value10());
        method.setParamValue11(model.getParam_value11());
        method.setParamValue12(model.getParam_value12());
        method.setParamValue13(model.getParam_value13());
        method.setParamValue14(model.getParam_value14());
        method.setParamValue15(model.getParam_value15());
        method.setQrcode(model.getQrcode());
        method.setRemark(model.getRemark());
        method.setUpdateTime(new Date());
        boolean state = this.c2cPaymentMethodService.updateById(method);
        if (state) {
            redisTemplate.opsForValue().set(RedisKeys.C2C_PAYMENT_METHOD_ID + method.getUuid(), method);
            Map<String, C2cPaymentMethod> map = (Map<String, C2cPaymentMethod>) redisTemplate.opsForValue().get(RedisKeys.C2C_PAYMENT_METHOD_PARTY_ID + method.getPartyId().toString());
            if (null == map) {
                map = new ConcurrentHashMap<String, C2cPaymentMethod>();
            } else {
                map.remove(method.getUuid());
            }
            map.put(method.getUuid(), method);
            redisTemplate.opsForValue().set(RedisKeys.C2C_PAYMENT_METHOD_PARTY_ID + method.getPartyId().toString(), map);
            Map<String, String> map1 = (Map<String, String>) redisTemplate.opsForValue().get(RedisKeys.C2C_PAYMENT_METHOD_ID_TYPE);
            if (null == map1) {
                map1 = new ConcurrentHashMap<String, String>();
            } else {
                map1.remove(method.getUuid());
            }
            map1.put(method.getUuid(), String.valueOf(method.getMethodType()));
            redisTemplate.opsForValue().set(RedisKeys.C2C_PAYMENT_METHOD_ID_TYPE, map1);
        }
        log += MessageFormat.format(",id:{0},新用户PARTY_ID:{1},新支付方式模板:{2},新支付方式类型:{3},新支付方式名称:{4},新支付方式图片:{5},新真实姓名:{6},"
                        + "新参数名1:{7},新参数值1:{8},新参数名2:{9},新参数值2:{10},新参数名3:{11},新参数值3:{12},新参数名4:{13},新参数值4:{14},新参数名5:{15},新参数值5:{16},"
                        + "新参数名6:{17},新参数值6:{18},新参数名7:{19},新参数值7:{20},新参数名8:{21},新参数值8:{22},新参数名9:{23},新参数值9:{24},新参数名10:{25},新参数值10:{26},"
                        + "新参数名11:{27},新参数值11:{28},新参数名12:{29},新参数值12:{30},新参数名13:{31},新参数值13:{32},新参数名14:{33},新参数值14:{34},新参数名15:{35},新参数值15:{36},"
                        + "新支付二维码:{37},新备注:{38},新创建时间:{39},新更新时间:{40}",
                method.getUuid(), method.getPartyId(), method.getMethodConfigId(), method.getMethodType(), method.getMethodName(), method.getMethodImg(), method.getRealName(),
                method.getParamName1(), method.getParamValue1(), method.getParamName2(), method.getParamValue2(), method.getParamName3(), method.getParamValue3(), method.getParamName4(), method.getParamValue4(), method.getParamName5(), method.getParamValue5(),
                method.getParamName6(), method.getParamValue6(), method.getParamName7(), method.getParamValue7(), method.getParamName8(), method.getParamValue8(), method.getParamName9(), method.getParamValue9(), method.getParamName10(), method.getParamValue10(),
                method.getParamName11(), method.getParamValue11(), method.getParamName12(), method.getParamValue12(), method.getParamName13(), method.getParamValue13(), method.getParamName14(), method.getParamValue14(), method.getParamName15(), method.getParamValue15(),
                method.getQrcode(), method.getRemark(), method.getCreateTime(), method.getUpdateTime());
        User user = userCacheService.currentUser();
        logService.saveLog(user, log, UserConstants.LOG_CATEGORY_C2C);
        return Result.succeed(null);
    }

    /**
     * 获取 支付方式 列表
     */
    @RequestMapping("myList")
    @ApiOperation("获取我的 支付方式 列表")
    public Result list(@RequestParam String language) {
        List<C2cPaymentMethod> list = new ArrayList<C2cPaymentMethod>();
        Map<String, C2cPaymentMethod> map = this.c2cPaymentMethodService.getByPartyId(SecurityUtils.getUser().getUserId());
        if (null != map && 0 != map.size()) {
            for (C2cPaymentMethod method : map.values()) {
                if (null != method) {
                    if (com.yami.trading.common.util.StringUtils.isNotEmpty(method.getMethodImg())) {
                        String path = Constants.WEB_URL + "/public/showimg!showImg.action?imagePath=" + method.getMethodImg();
                        method.setMethodImg(path);
                    }
                    list.add(this.c2cTranslateService.translatePm(method, language));
                }
            }
        }
        return Result.succeed(list);
    }

    @ApiOperation(value = "删除我的收款方式")
    @RequestMapping("deletepPymentMethod")
    public Result<List<C2cPaymentMethod>> deletepPymentMethod(@Valid IdModel model) {
        c2cPaymentMethodService.removeById(model.getId());
        return Result.succeed(null);
    }


}
